import axios from "axios";
import { Message } from "element-ui";
// import { h } from "js-beautif-libs";
import { responseFun } from "../utils/js-beautif-libs/http";
import store from "@/store";
import localCache from "@/utils/cache";

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers["Authorization"] = localCache.getCache("token");
    }
    config.header = {
      Accept: "application/json, text/plain, */*",
      "Content-Type": "application/json",
    };
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    return responseFun(response, store, Message);
  },
  (error) => {
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export const get = (url, params = {}, ...config) => {
  return service({
    url,
    params,
    ...config,
    method: "get",
  });
};

export const post = (url, params = {}, ...config) => {
  return service({
    url,
    data: params,
    ...config,
    method: "post",
  });
};

export default service;
